package com.atguigu.yygh.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.common.result.R;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.user.util.ConstantPropertiesUtil;
import com.atguigu.yygh.user.util.HttpClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:ahang
 * @create:2022-09-07 20:53
 * @Description:
 */
@Controller
@RequestMapping("/api/user/wx")
public class WxApiController {

    @Autowired
    private UserInfoService userInfoService;

    //给微信二维码传递参数
    @GetMapping("getLoginParam")
    @ResponseBody
    public R getLoginParam() throws UnsupportedEncodingException {
        String appid = ConstantPropertiesUtil.WX_OPEN_APP_ID;
        String scope = "snsapi_login";
        String redirectUri = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        redirectUri = URLEncoder.encode(redirectUri, "utf-8");
        String state = System.currentTimeMillis()+"";

        Map<String,Object> map = new HashMap<>();
        map.put("appid",appid);
        map.put("scope",scope);
        map.put("redirectUri",redirectUri);
        map.put("state",state);

        return R.ok().data(map);
    }


    //扫码之后的回调函数
    @GetMapping("callback")
    public String callback(String code) throws Exception{
        //1、参数：code  微信端的临时票据
        //2、根据临时票据获取access_token=openid
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid="+ConstantPropertiesUtil.WX_OPEN_APP_ID+"&" +
                "secret="+ConstantPropertiesUtil.WX_OPEN_APP_SECRET+"&" +
                "code="+code+"&" +
                "grant_type=authorization_code";
        String s = HttpClientUtils.get(url, "utf-8");
        JSONObject jsonObject = JSONObject.parseObject(s);
        //3、获取返回值
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //4、根据openid查询user_info表中是否存在当前微信用户
        UserInfo userInfo = userInfoService.selectWeixinByOpenid(openid);
        if(userInfo==null){
            userInfo = new UserInfo();
            //5、根据access_token=openid获取微信昵称
            String url2 = "https://api.weixin.qq.com/sns/userinfo?" +
                    "access_token="+access_token+"&openid="+openid;

            String s1 = HttpClientUtils.get(url2);
            JSONObject jsonObject1 = JSONObject.parseObject(s1);

            //获取昵称
            String nickname = jsonObject1.getString("nickname");
            //封装保存数据库
            userInfo.setOpenid(openid);
            userInfo.setNickName(nickname);

            userInfoService.save(userInfo);

        }
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
            if(StringUtils.isEmpty(name)){
                name = userInfo.getPhone();
            }
        }

        //jwt令牌
        String token = JwtHelper.createToken(userInfo.getId(), name);


        name = URLEncoder.encode(name,"utf-8");
        String phone = userInfo.getPhone();
        if(StringUtils.isEmpty(phone)){
            //前端绑定手机号
            return "redirect:http://localhost:3000/weixin/callback?name="+name+"&token="+token+"&openid="+userInfo.getOpenid();
        }else{
            //前端不需要绑定
            return "redirect:http://localhost:3000/weixin/callback?name="+name+"&token="+token+"&openid=";
        }

    }
}
